import { Controller } from "egg";

const fs = require("fs");
const sitemap = require("sitemap-nodejs");
const axios = require("axios");
const cheerio = require("cheerio");

export default class HomeController extends Controller {
  public async index() {
    sitemap.init({
      href: "https://www.thosefree.com/web",
      save_path: "sitemap.txt",
      show_url: true,
    });
    const { ctx } = this;
    ctx.body = {
      data: "hello world",
    };
  }

  public async getThosefree() {
    // const { token, ID } = await this.getLogin();

    const data = fs.readFileSync("sitemap.txt", "utf8");
    const { ctx } = this;
    const urls = data.split("\n");
    const arr: any = [];
    for (const item of urls.slice(0, 1)) {
      console.log(item);
      try {
        const res = await axios.get(item);
        var $ = cheerio.load(res.data);
        const CateName = $(".crumbs a:nth-child(2)").text();
        const match = $(".post-meta")
          .text()
          .match(/(\d{4}-\d{2}-\d{2})/);
        const PostTime = match && match[1];
        const content = $(".post-content").text();
        const href = $("#single-aside-content .side-btn-text").text();
        const hrefHtml = `<p class="putong">
          官网链接:<a href="${href}" target="_blank">${href}</a>
        </p>`;

        if (
          !content ||
          ![
            "前端资源",
            "前端UI组件库",
            "前端开源项目",
            "免费前端教程",
          ].includes(CateName)
        ) {
          continue;
        }

        const Tag: any[] = [];
        $(".tag-wrap.post-header-tags a").each((index, element) => {
          Tag.push($(element).text());
        });

        arr.push({
          Title: $("h1").text(),
          Type: 0,
          CateName: CateName,
          AuthorID: 1,
          Intro: $('meta[name="description"]').attr("content"),
          Tag: Tag.join(","),
          PostTime,
          Content: hrefHtml + content,
          Status: "0",
        });
      } catch (error) {
        console.log(error);
      }
    }

    fs.writeFile("file.json", JSON.stringify(arr), "utf8", (err) => {
      if (err) {
        console.error("写入文件时发生错误：", err);
        return;
      }
      console.log("写入文件成功！");
    });
    ctx.body = arr;

    // const formData = new URLSearchParams();
    // const token =
    //   "YWRtaW58fHw0ZjQ4OTAzNTNlMWVjNGI5MzVmZTYxYmY2ZjJiYTc1MzYzM2RiOGU0ZDNkZDFmNzMxYTQxMTAzNzBjMDZmN2RmMTY5MjAxODk0OQ==";
    // formData.append("token", token);
    // for (const item of arr) {
    //   Object.entries(item).map((item: any) => {
    //     formData.append(item[0], item[1]);
    //   });
    // }

    // const res = await axios.post(
    //   "http://115.159.31.19/zb_system/api.php?mod=post&act=post",
    //   formData.toString(),
    //   {
    //     headers: {
    //       "Content-Type": "application/json; charset=utf-8",
    //       Authorization: `Bearer ${token}`,
    //     },
    //   }
    // );
    // console.log(res.data);
  }

  // 登录zblog后台获取token
  public async getLogin() {
    const {
      data: {
        data: {
          token,
          user: { ID },
        },
      },
    } = await axios.post(
      "http://115.159.31.19/zb_system/api.php?mod=member&act=login",
      {
        username: "admin",
        password: "Aa123456",
        savedate: 30,
      }
    );

    const { ctx } = this;
    const data = {
      token,
      ID,
    };

    ctx.body = data;
    return data;
  }
}
